package com.zhou.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zhou.constant.MessageConstant;
import com.zhou.dao.PermissionMapper;
import com.zhou.dao.RoleMapper;
import com.zhou.dao.UserMapper;
import com.zhou.entity.PageResult;
import com.zhou.entity.QueryPageBean;
import com.zhou.entity.Result;
import com.zhou.pojo.Permission;
import com.zhou.pojo.Role;
import com.zhou.pojo.User;
import com.zhou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    private BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

    /**
     * 根据用户名查询用户信息和关联的角色信息,同时需要查询角色关联的权限信息
     *
     * @param username
     * @return
     */
    @Override
    public User findByUsername(String username) {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            return null;
        }
        Integer userId = user.getId();
        Set<Role> roles = roleMapper.findByUserId(userId);
        if (roles != null && roles.size() > 0) {
            for (Role role : roles) {
                Integer roleId = role.getId();
                Set<Permission> permissions = permissionMapper.findByRoleId(roleId);
                if (permissions != null && permissions.size() > 0) {
                    role.setPermissions(permissions);
                }
            }
            user.setRoles(roles);
        }
        return user;
    }

    /**
     * 分页查询
     *
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<User> page = userMapper.findByPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增用户
     *
     * @param user
     * @param roleIds
     * @return
     */
    @Override
    public Result add(User user, Integer[] roleIds) {
        //先判断用户名是否存在，确保用户名的唯一性（t_user）
        long count = userMapper.findExist(user.getUsername());
        if (count > 0) {
            return new Result(false, "该用户名已经存在,无法创建");
        } else {
            String password = bCryptPasswordEncoder.encode(user.getPassword());
            user.setPassword(password);
            userMapper.insert(user);
            setUserAndRole(user.getId(), roleIds);
            return new Result(true, MessageConstant.ADD_USER_SUCCESS);
        }
    }

    /**
     * 建立用户和角色的多对多关系
     *
     * @param userId
     * @param roleIds
     */
    private void setUserAndRole(Integer userId, Integer[] roleIds) {
        if (roleIds != null && roleIds.length > 0) {
            Map<String, Integer> map = null;
            for (Integer roleId : roleIds) {
                map = new HashMap<>();
                map.put("user_id", userId);
                map.put("role_id", roleId);
                userMapper.setUserAndRole(map);
            }
        }
    }

    /**
     * 根据用户id查询该用户所有的角色
     *
     * @param id
     * @return
     */
    @Override
    public Map findByIdWithAllRole(Integer id) {
        //根据用户id查询 用户的基本信息
        User user = userMapper.selectByPrimaryKey(id);
        //查询所有的角色信息
        List<Role> roleList = roleMapper.findAll();
        //根据用户的id 查询用户对应的角色id
        List<Integer> roleIds = roleMapper.findRoleById(id);
        HashMap<String, Object> map = new HashMap<>();
        map.put("formData", user);
        map.put("tableData", roleList);
        map.put("roleIds", roleIds);
        return map;
    }

    /**
     * 修改当前用户基本信息
     *
     * @param user
     * @param roleIds
     */
    @Override
    public void edit(User user, Integer[] roleIds) {
        //修改用户表基本信息，操作检查组t_user表
        userMapper.updateByPrimaryKeySelective(user);
        //清理当前用户关联的角色，操作中间关系表 t_user_role 表
        userMapper.deleteAssociation(user.getId());
        //重新建立当前用户和角色的关联关系，操作 t_user_role 表
        setUserAndRole(user.getId(), roleIds);
    }

    /**
     * 根据用户id删除用户
     *
     * @param id
     * @return
     */
    @Override
    public Result deleteById(Integer id) {
        //判断删除的用户是否存在管理员角色
        Set<Role> roles = roleMapper.findByUserId(id);//使用set去重
        if (roles.size() > 0) {
            for (Role role : roles) {
                if (role.getKeyword().equals("ROLE_ADMIN")) {
                    return new Result(false, "该用户为系统管理员权限不可删除");
                }
            }
        }
        //删除用户和角色的关联表(t_user_role)的数据,根据用户id进行删除
        userMapper.deleteAssociation(id);
        //删除用户
        userMapper.deleteByPrimaryKey(id);
        return new Result(true, MessageConstant.DELETE_USER_SUCCESS);
    }

    /**
     * 根据id获取用户信息
     *
     * @param id
     * @return
     */
    @Override
    public User showUsername(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    /**
     * 修改用户密码
     *
     * @param map
     * @return
     */
    @Override
    public Result modifyPassword(Map map) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        //加密
        password = bCryptPasswordEncoder.encode(password);
        user.setPassword(password);
        //修改密码
        userMapper.changePassword(user);
        return new Result(true, MessageConstant.CHANEG_PASSWORD_USER_SUCCESS);
    }
}
